package erp.server.user.service.impl;

import erp.server.base.exception.ServiceException;
import erp.server.base.response.StatusCode;
import erp.server.user.entity.dto.CreateUserDTO;
import erp.server.user.entity.dto.EditUserDTO;
import erp.server.user.entity.dto.LoginDTO;
import erp.server.user.entity.pojo.User;
import erp.server.user.entity.vo.MemberVO;
import erp.server.user.entity.vo.UserVO;
import erp.server.user.mapper.UserMapper;
import erp.server.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public void createUser(CreateUserDTO createUserDTO) {
        User user = new User();
        BeanUtils.copyProperties(createUserDTO,user);
        user.setCreateTime(new Date());
        userMapper.createUser(user);
    }

    @Override
    public UserVO login(LoginDTO loginDTO) {
        User userInfo = userMapper.selectUserByUsername(loginDTO.getUsername());
        if (userInfo == null){
            throw new ServiceException(StatusCode.USERNAME_DOES_NOT_EXIST);
        }
        if (!loginDTO.getPassword().equals(userInfo.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(userInfo,userVO);
            return userVO;
        }
    }

    @Override
    public List<MemberVO> selectMember(Long organizationID) {
        return userMapper.selectMember(organizationID);
    }

    @Override
    public void editUserInfo(EditUserDTO editUserDTO) {
        User user = new User();
        BeanUtils.copyProperties(editUserDTO,user);
        userMapper.editUser(user);
    }
}
